package com.example.jdbc0914.servlet;

import com.example.jdbc0914.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author ：lqs
 * @date ：Created in 2023/9/14 15:12
 * @description：
 * @modified By：
 * @version:
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserDao userDao=new UserDao();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受账号和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用UserDao中的方法
        Map<String, Object> map = userDao.findByUsernameAndPwd(username, password);
        //判断返回的结果
        if (map!=null){
            //表示登陆成功
            //获取Session对象
            HttpSession session = req.getSession();
            //把用户的消息保存到session中
            session.setAttribute("user",map);
            //重定向
            resp.sendRedirect("/main.jsp");
        }else{
            req.setAttribute("msg","<font color='red'>账号或密码错误</font>");
            //表示登录失败
            req.getRequestDispatcher("/login.jsp").forward(req,resp);//转发跳转。
        }


    }
}

